package com.abcdefg.webpagechatprojectbymyself.api;

import com.abcdefg.webpagechatprojectbymyself.mapper.UserMapper;
import com.abcdefg.webpagechatprojectbymyself.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("UserApi")
@RestController
public class UserApi {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    public Object login(String username, String password, HttpServletRequest request) {
        User user=userMapper.selectUserByUsername(username);
        if(user==null || !user.getPassword().equals(password)) {
            return new User();
        }
        //如果登录成功，则创建会话
        HttpSession session=request.getSession(true);
        //将通过userMapper获取到的user存储到“user”这个会话中
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }
    @PostMapping("register")
    public Object register(String username, String password){
        User user;
        try{
            user=new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insertUser(user);
            log.info("userId:"+user.getUserId());
            System.out.println("注册成功！");
        }catch (DuplicateKeyException e){
            //这个异常用于处理向数据库中插入字段，违背了主键的唯一性
            System.out.println("注册失败！");
            user=new User();
        }
        user.setPassword("");

        return user;
    }

    //用来实现主页面左上角名字显示
    @GetMapping("userInfo")
    public Object getUserInfo(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        if(session==null){
            System.out.println("获取不到当前Session对象！！！");
            return new User();
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            System.out.println("获取不到当前User对象！！！");
            return  new User();
        }
        user.setPassword("");
        return user;
    }
}
